import { defineConfig, loadEnv } from "vite";
import { resolve } from "path";
import vue from "@vitejs/plugin-vue";
import { createHtmlPlugin } from "vite-plugin-html";
import viteCompression from "vite-plugin-compression";
import analyzer from "rollup-plugin-analyzer";
import pkgJson from "./package.json";
import { wrapperEnv } from "./scripts/utils";

function pathResolve(dir) {
  return resolve(process.cwd(), ".", dir);
}

export default defineConfig(({ command, mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);

  const isBuild = command === "build";

  const { VITE_SITE_URL, VITE_PORT, VITE_GLOB_APP_TITLE, VITE_DROP_CONSOLE, VITE_APP_SHORT_NAME } = wrapperEnv(env);

  return {
    root,
    resolve: {
      alias: {
        "@": pathResolve("src"),
        moment: "dayjs",
      },
    },
    define: {
      "import.meta.env.ELECTRON": false,
      "import.meta.env.VITE_GLOB_APP_TITLE": JSON.stringify(VITE_GLOB_APP_TITLE),
      "import.meta.env.VITE_APP_SHORT_NAME": JSON.stringify(pkgJson.name),
      "import.meta.env.VITE_APP_VERSION": `"${pkgJson.version}"`
    },
    plugins: [
      vue({
        template: {
          compilerOptions: {
            isCustomElement: tag => /^micro-app/.test(tag)
          }
        }
      }),
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: VITE_GLOB_APP_TITLE,
            siteUrl: "",
            injectScript: "",
          },
        },
      }),
      // visualizer(),
      analyzer({ summaryOnly: true }),
      // 构建压缩文件
      viteCompression({
        // 是否在控制台输出压缩结果，默认为 true
        verbose: true,
        // 是否禁用压缩，默认为 false
        disable: false,
        // 启用压缩的文件大小最小限制，单位字节（byte），默认为 0，1b(字节)=8bit(比特), 1KB=1024B
        threshold: 10240, // 即10kb以上即会压缩
        // 采用的压缩算法，默认是 gzip
        algorithm: "gzip",
        // 生成的压缩包后缀
        ext: ".gz",
      }),
    ],
    esbuild: {
      jsxFactory: "jsx",
      pure: ['console.log'], // 删除 console.log
      drop: ['debugger'], // 删除 debugger
    },
    build: {
      target: "es2015",
      minify: "terser",
      cssCodeSplit: true,
      // outDir: "/Users/cc/docker/louyu/vue/be_apps_ai",
      outDir: "./dist",
      // outDir: "/Users/cc/docker/louyu/vue/"+`${pkgJson.version}`,
      reportCompressedSize: false, //取消计算文件大小，加快打包速度
      terserOptions: {
        compress: {
          // 打包的时候可以移除console和debugger
          drop_debugger: true,
          keep_infinity: true,
          drop_console: VITE_DROP_CONSOLE,
        },
      },
      brotliSize: false,
      chunkSizeWarningLimit: 1500,
      sourcemap: false,
      rollupOptions: {
        input: 'index.html',
        output: {
          // 静态资源打包做处理
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          charset: false,
          modifyVars: {
            "primary-color": "#2878ff", // 全局主色
          },
          additionalData: '@import "./src/common/styles/base.less";',
        },
      },
    },
    server: {
      host: '0.0.0.0', 
      port: VITE_PORT,
      cors: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      proxy: {
        "/api": {
          target: VITE_SITE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    clearScreen: false,
  };
});
 